// personal-info.ts
Component({
  data: {
    userInfo: {
      avatar: '',
      nickName: '',
      phone: '',
      birthday: '',
      gender: 'secret'
    }
  },

  lifetimes: {
    attached() {
      this.loadUserInfo()
    }
  },

  methods: {

    handlerGobackClick() {
      wx.navigateBack({
        delta: 1
      })
    },
    loadUserInfo() {
      const userInfo = wx.getStorageSync('userInfo') || {
        avatar: '',
        nickName: '',
        phone: '',
        birthday: '',
        gender: 'secret'
      }
      this.setData({ userInfo })
    },

    chooseAvatar() {
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const avatar = res.tempFilePaths[0]
          this.setData({
            'userInfo.avatar': avatar
          })
        },
        fail: () => {
          wx.showToast({
            title: '选择头像失败',
            icon: 'none'
          })
        }
      })
    },

    onNickNameInput(e: any) {
      this.setData({
        'userInfo.nickName': e.detail.value
      })
    },

    onPhoneInput(e: any) {
      this.setData({
        'userInfo.phone': e.detail.value
      })
    },

    onBirthdayChange(e: any) {
      this.setData({
        'userInfo.birthday': e.detail.value
      })
    },

    onGenderChange(e: any) {
      this.setData({
        'userInfo.gender': e.detail.value
      })
    },

    saveInfo() {
      const { userInfo } = this.data
      
      if (!userInfo.nickName) {
        wx.showToast({
          title: '请输入昵称',
          icon: 'none'
        })
        return
      }

      if (userInfo.phone && userInfo.phone.length !== 11) {
        wx.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }

      wx.setStorageSync('userInfo', userInfo)
      
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        complete: () => {
          wx.navigateBack()
        }
      })
    }
  }
})